<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>简单的小游戏</title>
  <style>
    #game-container {
      width: 400px;
      height: 300px;
      position: relative;
      border: 1px solid black;
    }

    #player {
      width: 50px;
      height: 50px;
      background-color: red;
      position: absolute;
      top: 125px;
      left: 175px;
    }

    #target {
      width: 30px;
      height: 30px;
      background-color: green;
      position: absolute;
      top: 135px;
      left: 355px;
    }
  </style>
</head>
<body>
  <h1>简单的小游戏</h1>

  <div id="game-container">
    <div id="player"></div>
    <div id="target"></div>
  </div>

  <script>
    // 获取游戏容器和玩家元素
    const gameContainer = document.getElementById('game-container');
    const player = document.getElementById('player');

    // 监听键盘按下事件
    document.addEventListener('keydown', (event) => {
      const { top, left } = player.getBoundingClientRect(); // 获取玩家当前的位置

      // 根据按下的键盘按键移动玩家
      if (event.key === 'ArrowUp' && top > 0) {
        player.style.top = `${top - 10}px`;
      } else if (event.key === 'ArrowDown' && top < gameContainer.clientHeight - player.clientHeight) {
        player.style.top = `${top + 10}px`;
      } else if (event.key === 'ArrowLeft' && left > 0) {
        player.style.left = `${left - 10}px`;
      } else if (event.key === 'ArrowRight' && left < gameContainer.clientWidth - player.clientWidth) {
        player.style.left = `${left + 10}px`;
      }

      // 检查是否成功达到目标
      const target = document.getElementById('target');
      const targetRect = target.getBoundingClientRect();
      if (
        top >= targetRect.top &&
        top + player.clientHeight <= targetRect.bottom &&
        left >= targetRect.left &&
        left + player.clientWidth <= targetRect.right
      ) {
        alert('恭喜你成功达到目标！');
      }
    });
  </script>
</body>
</html>
